//
//  MSNetworkManager.m
//  ZuLinProject
//
//  Created by ypj on 2021/12/14.
//

#import "MSNetworkManager.h"
#import "ResponseClass.h"
#import "Filter.h"
#import "LoginPageViewController.h"

@implementation MSNetworkManager

+ (AFHTTPSessionManager *)manager{
    static AFHTTPSessionManager *manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [AFHTTPSessionManager manager];
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", nil];
        manager.requestSerializer.timeoutInterval = 10;
    });
    return manager;
}

///请求头设置
+ (NSDictionary *)setHeader
{
    YLUserInfo *InfoModel = [YLUserMgr fetchUser];
    NSString *str;
    if (InfoModel.authorization.length > 0) {
        str = [NSString stringWithFormat:@"Bearer %@",InfoModel.authorization];
    } else {
        str = @"Basic dGVzdDp0ZXN0";
    }
    return @{@"authorization":str,@"userType":@"1",@"type":@"1"};
}

+ (void)postRevertUrl:(NSString *)url
            params:(NSDictionary *)body
             formData:(NSArray *)files
              success:(NetworkSuccess)success
              failure:(NetworkFail)failure
          withShowHud:(BOOL)isShow{
    
    AFHTTPSessionManager *manager = [self manager];
    NSString *requestUrl = [NSString stringWithFormat:@"%@%@", DOMAIN_URL,url];
    requestUrl = [requestUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

    MBProgressHUD *hud;
    if (isShow) {
        hud = [MBProgressHUD showGif];
    }
    [manager POST:requestUrl parameters:body headers:[self setHeader] constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (YLUploadMedia *media in files) {
            NSData *data;
            switch (media.mediaType) {
                case YLUploadMediaTypeJpg: {
                    if ([media.obj isKindOfClass:NSString.class]) {
                        UIImage * img = [UIImage imageWithContentsOfFile:media.obj];
                        data = UIImageJPEGRepresentation(img, 1);
                        if (data) {
                            [formData appendPartWithFileData:data name:media.mimeName fileName:media.mediaName?media.mediaName:@"test.jpg" mimeType:@"image/jpg"];
                        }
                    } else if ([media.obj isKindOfClass:UIImage.class]) {
                        data = UIImageJPEGRepresentation(media.obj, 1);
                        if (data) {
                            [formData appendPartWithFileData:data name:media.mimeName fileName:media.mediaName?media.mediaName:@"test.jpg" mimeType:@"image/jpg"];
                        }
                    }
                }
                break;
                case YLUploadMediaTypeAmr: {
                  if ([media.obj isKindOfClass:NSString.class]) {
                        NSURL *url = [NSURL fileURLWithPath:media.obj];
                        data = [NSData dataWithContentsOfFile:url.path];
                        if (data) {
                            [formData appendPartWithFileData:data name:media.mimeName fileName:media.mediaName?media.mediaName:@"test.amr" mimeType:@"audio/amr"];
                        }
                    }
                }
                    break;
                case YLUploadMediaTypeMp4: {
                    if ([media.obj isKindOfClass:NSString.class]) {
                        NSURL *url = [NSURL fileURLWithPath:media.obj];
                        data = [NSData dataWithContentsOfFile:url.path];
                        if (data) {
                            [formData appendPartWithFileData:data name:media.mimeName fileName:media.mediaName?media.mediaName:@"test.mp4" mimeType:@"video/mp4"];
                        }
                    }
                }
                    break;
            }
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (isShow) {
            [hud hide];
        }
        
#ifdef DEBUG
        [self printResponseLog:responseObject url:url];
#endif
        
        if ([responseObject[@"success"] boolValue]==NO) {
            showAlert(responseObject[@"msg"]);
        }
        
        ResponseClass *response = [self convertToResponseClassWithDict:responseObject];
        [Filter filterWithServerCode:response withItem:response.data withPassBlock:success];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (isShow) {
            [hud hide];
        }
    }];
    
}

+ (void)postRevertUrl:(NSString *)url params:(NSDictionary *)params success:(NetworkSuccess)success failure:(NetworkFail)failure withShowHud:(BOOL)isShow{
    
   
    AFHTTPSessionManager *manager = [self manager];
    NSString *requestUrl = [NSString stringWithFormat:@"%@%@", DOMAIN_URL,url];
    requestUrl = [requestUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    NSLog(@"-----%@--------",requestUrl);
    
    NSLog(@"-----%@--------",[NSString toJson:params]);
    MBProgressHUD *hud;
    if (isShow) {
        hud = [MBProgressHUD showGif];
    }
    [manager POST:requestUrl parameters:params headers:[self setHeader] progress:^(NSProgress * _Nonnull downloadProgrefilterWithServerCodess) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (isShow) {
            [hud hide];
        }
#ifdef DEBUG
        [self printResponseLog:responseObject url:url];
#endif
        
        if ([responseObject[@"success"] boolValue]==NO) {
            showAlert(responseObject[@"msg"]);
        }
        
        ResponseClass *response = [self convertToResponseClassWithDict:responseObject];
        [Filter filterWithServerCode:response withItem:response.data withPassBlock:success];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (isShow) {
            [hud hide];
        }
        [Filter filterWithHttpCode:error withPassBlock:[failure copy]];
        [task resume];
    }];
       
}


+ (void)getRevertUrl:(NSString *)url params:(NSDictionary *)params success:(NetworkSuccess)success failure:(NetworkFail)failure withShowHud:(BOOL)isShow{
    
    
    AFHTTPSessionManager *manager = [self manager];
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    if (![url hasPrefix:@"http"]) {
        url = [NSString stringWithFormat:@"%@%@", DOMAIN_URL,url];
    }
    NSLog(@"-----%@--------",url);
    
    NSLog(@"-----%@--------",[NSString toJson:params]);
    MBProgressHUD *hud;
    if (isShow) {
        hud = [MBProgressHUD showGif];
    }
    [manager GET:url parameters:params headers:[self setHeader] progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (isShow) {
            [hud hide];
        }
#ifdef DEBUG
        [self printResponseLog:responseObject url:url];
#endif
        if ([responseObject[@"success"] boolValue]==NO) {
            showAlert(responseObject[@"msg"]);
        }
        
        ResponseClass *response = [self convertToResponseClassWithDict:responseObject];
        [Filter filterWithServerCode:response withItem:response.data withPassBlock:success];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (isShow) {
            [hud hide];
        }
        [Filter filterWithHttpCode:error withPassBlock:[failure copy]];
        [task resume];
    }];
       
}


+ (void)showNoNetAlert {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            UIWindow * keyWindow = [UIApplication sharedApplication].keyWindow;
            //NSLog(@"<<-- %@ -->>", keyWindow.subviews);
            for (UIView * subView in keyWindow.subviews) {
                if ([subView isKindOfClass:MBProgressHUD.class]) {
                    MBProgressHUD * hud = (MBProgressHUD *)subView;
                    [hud hideAnimated:NO];
                }
            }
            NSString * alertMsg = @"请手动前往手机设置内允许\"利行企业版\"使用网络";
            if ([[UIApplication sharedApplication] canOpenURL:[UIApplicationOpenSettingsURLString toUrl]]) {
                alertMsg = @"请检查您手机的网络设置, 并允许\"利行企业版\"使用网络";
            }
            UIAlertController * alertVC = [UIAlertController alertControllerWithTitle:@"网络开小差了" message:alertMsg preferredStyle:UIAlertControllerStyleAlert];
            [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
            [alertVC addAction:[UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
                 [[UIApplication sharedApplication] openURL:[UIApplicationOpenSettingsURLString toUrl]];
            }]];
            UIViewController * rootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
            //NSLog(@"<-- %s, %d --> %@", __FUNCTION__, __LINE__, rootVC);
            //防止重复弹
            if ([rootVC.presentedViewController isKindOfClass:UIAlertController.class]) {
                return;
            }
            //弹窗消失后才能重弹
            if (rootVC.presentedViewController) {
                [rootVC.presentedViewController dismissViewControllerAnimated:NO completion:^{
                    [rootVC presentViewController:alertVC animated:YES completion:nil];
                }];
            } else {
                [rootVC presentViewController:alertVC animated:YES completion:nil];
            }
        });
    });
}

+ (void)showLoginAlert {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            UIWindow * keyWindow = [UIApplication sharedApplication].keyWindow;
            //NSLog(@"<<-- %@ -->>", keyWindow.subviews);
            for (UIView * subView in keyWindow.subviews) {
                if ([subView isKindOfClass:MBProgressHUD.class]) {
                    MBProgressHUD * hud = (MBProgressHUD *)subView;
                    [hud hideAnimated:NO];
                }
            }

            //防止重复弹
            UIViewController * rootVC = keyWindow.rootViewController;
            //NSLog(@"<-- %s, %d --> %@", __FUNCTION__, __LINE__, rootVC);
            if ([rootVC.presentedViewController isKindOfClass:UIAlertController.class]) {
                return;
            }

            UIAlertController * alertVC = [UIAlertController alertControllerWithTitle:@"该账号已在其他设备登录" message:nil preferredStyle:UIAlertControllerStyleAlert];
            [alertVC addAction:[UIAlertAction actionWithTitle:@"登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
                [[SDWebImageDownloader  sharedDownloader] cancelAllDownloads];
                [SSKeyChainMgr delLoginToken];
                [YLUserMgr deleteUser];
                LoginPageViewController *pageVC=[[LoginPageViewController  alloc] init];
                UINavigationController *navigationVC=[[UINavigationController alloc] initWithRootViewController:pageVC];
                UIWindow  *mainWindow =[BaseViewController getCurrentWindow];
                [mainWindow setRootViewController:navigationVC];
            }]];
            [rootVC presentViewController:alertVC animated:YES completion:nil];
        });
    });
}


+(void)printResponseLog:(id)responseObject url:(NSString *)url{
#ifdef DEBUG
    if (responseObject) {
        NSData  *jsonData = [NSJSONSerialization dataWithJSONObject:responseObject options:0 error:nil];
        NSString *strJSON = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        strJSON           = [strJSON stringByReplacingOccurrencesOfString:@"\\" withString:@""];
        NSLog(@"接口返回数据内容 >>> \n👉👉👉👉👉👉👉👉👉👉👉👉👉👉👉👉👉👉👉👉\n%@\n @接口:%@👈👈👈👈👈👈👈👈👈👈👈👈👈👈👈👈👈👈👈👈\n\n", strJSON,url);
    }
#endif
    
}

+ (ResponseClass *) convertToResponseClassWithDict:(NSDictionary *) dict{
    if([[dict objectForKey:@"data"] isKindOfClass:[NSArray class]]){
        ResponseClass *rc = [ResponseClass<NSArray *> yy_modelWithDictionary:dict];
        return rc;
    }else{
        ResponseClass *rc = [ResponseClass<NSDictionary *> yy_modelWithDictionary:dict];
        return rc;
    }
}
+ (void)postFilesUrl:(NSString *)url
            params:(NSDictionary *)body
             formData:(YLUploadMedia *)media
              success:(NetworkSuccess)success
              failure:(NetworkFail)failure
          withShowHud:(BOOL)isShow{
    
    AFHTTPSessionManager *manager = [self manager];
    NSString *requestUrl = [NSString stringWithFormat:@"%@%@", DOMAIN_URL,url];
    requestUrl = [requestUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

    MBProgressHUD *hud;
    if (isShow) {
        hud = [MBProgressHUD showGif];
    }
    [manager POST:requestUrl parameters:body headers:[self setHeader] constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            NSData *data;
            switch (media.mediaType) {
                case YLUploadMediaTypeJpg: {
                    if ([media.obj isKindOfClass:NSString.class]) {
                        UIImage * img = [UIImage imageWithContentsOfFile:media.obj];
                        data = UIImageJPEGRepresentation(img, 1);
                        if (data) {
                            [formData appendPartWithFileData:data name:media.mimeName fileName:media.mediaName?media.mediaName:@"test.jpg" mimeType:@"image/jpg"];
                        }
                    } else if ([media.obj isKindOfClass:UIImage.class]) {
                        data = UIImageJPEGRepresentation(media.obj, 1);
                        if (data) {
                            [formData appendPartWithFileData:data name:media.mimeName fileName:media.mediaName?media.mediaName:@"test.jpg" mimeType:@"image/jpg"];
                        }
                    }
                }
                break;
                case YLUploadMediaTypeAmr: {
                  if ([media.obj isKindOfClass:NSString.class]) {
                        NSURL *url = [NSURL fileURLWithPath:media.obj];
                        data = [NSData dataWithContentsOfFile:url.path];
                        if (data) {
                            [formData appendPartWithFileData:data name:media.mimeName fileName:media.mediaName?media.mediaName:@"test.amr" mimeType:@"audio/amr"];
                        }
                    }
                }
                    break;
                case YLUploadMediaTypeMp4: {
                    if ([media.obj isKindOfClass:NSString.class]) {
                        NSURL *url = [NSURL fileURLWithPath:media.obj];
                        data = [NSData dataWithContentsOfFile:url.path];
                        if (data) {
                            [formData appendPartWithFileData:data name:media.mimeName fileName:media.mediaName?media.mediaName:@"test.mp4" mimeType:@"video/mp4"];
                        }
                    }
                }
                    break;
            }
        
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (isShow) {
            [hud hide];
        }
        
#ifdef DEBUG
        [self printResponseLog:responseObject url:url];
#endif
        
        if ([responseObject[@"success"] boolValue]==NO) {
            showAlert(responseObject[@"msg"]);
        }
        
        ResponseClass *response = [self convertToResponseClassWithDict:responseObject];
        [Filter filterWithServerCode:response withItem:response.data withPassBlock:success];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (isShow) {
            [hud hide];
        }
    }];
    
}
@end
